//
//  SouSuoViewController.m
//  diaoyuren
//
//  Created by 钓鱼人 on 16/2/18.
//  Copyright © 2016年 game. All rights reserved.
//

#import "SouSuoViewController.h"
#import "HotSearchCell.h"
#import "SouSuoXQController.h"

@interface SouSuoViewController ()<UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate,HotBtnProtocol,UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet UITextField *SousuoTextField;
@property(nonatomic,strong)UITableView *rootTableView;

@property (nonatomic,strong) NSMutableArray *serchAry;

/**
 *  写本地文件路径
 */
@property (nonatomic,copy) NSString *path;

@end

@implementation SouSuoViewController

-(NSMutableArray *)serchAry{
    if (!_serchAry) {
        _serchAry = [NSMutableArray array];
    }
    return _serchAry;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
     self.app.myTabBar.tabBar.hidden = YES;
    self.navigationController.navigationBar.hidden=YES;
    
     StatusBlack;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.path = [self CreatPath];
    self.serchAry = [NSMutableArray arrayWithContentsOfFile:self.path];
    
    [self.SousuoTextField becomeFirstResponder];
    self.SousuoTextField.delegate=self;
    
    self.SousuoTextField.leftView = [self textFileLweftView];
    self.SousuoTextField.leftViewMode=UITextFieldViewModeAlways;
    [self AboutRootTableView];
}

/**
 *  创建存文件的路径
 */
-(NSString *)CreatPath{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *path = [NSString stringWithFormat:@"%@/Library/Caches/Search",NSHomeDirectory()];;
    
    [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];//在路径创建文件夹
    NSString *filePath = [NSString stringWithFormat:@"%@/Search.plist",path];
    return filePath;
}

/**
 *  textFile左边视图  放大镜
 */
-(UIView *)textFileLweftView{
    UIView *bacView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, H(self.SousuoTextField), H(self.SousuoTextField))];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"btn-search-grey"]];
    imageView.frame = CGRectMake(5,5,W(bacView)-10,W(bacView)-10);
    [bacView addSubview:imageView];

    return bacView;
}
//
#pragma mark - 点击取消按钮
- (IBAction)CancelAction:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
//#pragma mark  - 关于tableview
-(void)AboutRootTableView
{
    self.rootTableView=[[UITableView alloc] initWithFrame:CGRectMake(0,64,[UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) style:UITableViewStylePlain];
    self.rootTableView.showsVerticalScrollIndicator=NO;
    self.rootTableView.backgroundColor=[UIColor colorWithRed:239/255.0 green:239/255.0 blue:239/255.0 alpha:1.0];
    [self.view addSubview:self.rootTableView];

    self.rootTableView.dataSource=self;
    self.rootTableView.delegate=self;
    self.rootTableView.tableFooterView=[[UIView alloc] init];
    self.rootTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.rootTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.rootTableView registerClass:[HotSearchCell class] forCellReuseIdentifier:@"HotSearchCell"];
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    if ([string isEqualToString:@"\n"]) {
        [self MakeSearhAryWhithString:textField.text];
    }
    return YES;
}

#pragma mark - 击热卖选项按钮调代理方法-(void)ClickHotBtn
-(void)ClickHotBtnWhithString:(NSString *)string
{
    [self MakeSearhAryWhithString:string];
}

/**
 *  操作数组  点击选择后 对数据进行更改 存档 并进行页面跳转
 */
-(void)MakeSearhAryWhithString:(NSString *)string{
//    
   SouSuoXQController *ctl=[SouSuoXQController new];
    ctl.searchString = string;
    [self.navigationController pushViewController:ctl animated:YES];
    self.SousuoTextField.text = string;
    
    if (self.serchAry.count==0) {
        [self.serchAry addObject:string];
    }
    
    NSInteger have = 1;
    NSInteger index =0 ;//如果数组中还没有内容 则直接把搜索内容加入数组
    for (NSString *ssst in self.serchAry) {
        
        if ([ssst isEqualToString:string]) {
            have = 2;
            index = [self.serchAry indexOfObject:ssst];
        }
    }
    
    if (have==1) {//如果没有包含本次搜索内容则将搜索内容放到数组的第一位
        [self.serchAry insertObject:string atIndex:0];
    }
    
    if (have==2) {//如果包含本次搜索内容则将雨来包含的内容删除，再将本次搜索内容放到数组的第一位
        [self.serchAry removeObjectAtIndex:index];
        [self.serchAry insertObject:string atIndex:0];
    }
    
    [self.serchAry writeToFile:self.path atomically:YES];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.rootTableView reloadData];
    });
}


#pragma mark - scrollview代理方法
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self.SousuoTextField endEditing:YES];
}
#pragma mark - tableview代理方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return 1;
    }
    return self.serchAry.count;
}

-(void)ClearSeach:(UIButton *)btn{
    [self.serchAry removeAllObjects];
    [self.rootTableView reloadData];
    [self.serchAry writeToFile:self.path atomically:YES];
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        HotSearchCell*cell=[tableView dequeueReusableCellWithIdentifier:@"HotSearchCell"];
        cell.HotArr= self.hotSeachAry;
        cell.delegate=self;
        return cell;
    }else{
    
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.textLabel.text=self.serchAry[indexPath.row];
    cell.textLabel.font = font(SCREEN_WIDTH*0.04);
    [self Linview:CGRectMake(0, 33.7, SCREEN_WIDTH, 0.3) BackgroundColor:linColor AddView:cell.contentView];
        return cell;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
// ***热门搜索标签如果由网络请求而来，则修改此处cell高度****；
        return 90;
    }
    return 34;
}

-(CGFloat )tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)sectio{
    return 35;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UILabel *lab=  [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 35)];
    lab.userInteractionEnabled = YES;
    lab.font= font(SCREEN_WIDTH*0.045);
    lab.textColor = textcolor;
    if (section==0) {
        lab.text = @"  热门搜索";
    }else{
        lab.text = @"  最近搜索";
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.layer.borderColor  = mainColor.CGColor;
        btn.layer.borderWidth = 0.8;
        [btn setTitleColor:mainColor forState:UIControlStateNormal];
        btn.titleLabel.font = font(SCREEN_WIDTH*0.05);
        
        radius(btn, 3);
        btn.frame = CGRectMake(SCREEN_WIDTH-115, 5, 100, H(lab)-10);
        [btn setTitle:@"清空搜索记录" forState:UIControlStateNormal];
        btn.titleLabel.font = font(SCREEN_WIDTH*0.042);
        [btn addTarget:self action:@selector(ClearSeach:) forControlEvents:UIControlEventTouchUpInside];
        
        if(self.serchAry.count!=0){
            [lab addSubview:btn];
        }else{
            [btn removeFromSuperview];
        }
    }
    return lab;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section==1) {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        [self MakeSearhAryWhithString:cell.textLabel.text];
    }
    
}

@end